package com.pig4cloud.pigx.wallet.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pigx.common.customize.utils.id.IdWorker;
import com.pig4cloud.pigx.wallet.entity.ContractAccountDetail;
import com.pig4cloud.pigx.wallet.entity.LiquidationExpensesStatistics;
import com.pig4cloud.pigx.wallet.enums.WalletContractAccountDetailEnum;
import com.pig4cloud.pigx.wallet.mapper.ContractAccountDetailMapper;
import com.pig4cloud.pigx.wallet.mapper.LiquidationExpensesStatisticsMapper;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 强平清算费用定时汇总记录
 */
@Component
@EnableScheduling
@AllArgsConstructor
public class LiquidationExpensesStatisticsTask {

	private final LiquidationExpensesStatisticsMapper statisticsMapper;

	private final ContractAccountDetailMapper detailMapper;

	private final IdWorker idWorker;

	/**
	 * 每日八点计算
	 */
	@Scheduled(cron = "0 0 8 * * ?")
	public void liquidationExpensesStatisticsTask() {
		LocalDateTime time = LocalDateTime.now();
		List<ContractAccountDetail> details = detailMapper.selectList(new QueryWrapper<ContractAccountDetail>() {{
			select("sum(amount) amount", "symbol_id","symbol_name");
			eq("business_type", WalletContractAccountDetailEnum.BusinessType.CLEAR_FEE.getValue());
			eq("operation_type", WalletContractAccountDetailEnum.OperationType.MINUS.getValue());
			groupBy("symbol_id","symbol_name");
		}});
		details.forEach(e -> {
			LiquidationExpensesStatistics statistics = new LiquidationExpensesStatistics();
			statistics.setId(idWorker.nextId());
			statistics.setSymbolId(e.getSymbolId());
			statistics.setSymbolName(e.getSymbolName());
			statistics.setCost(e.getAmount());
			statistics.setCreateTime(time);
			statisticsMapper.insert(statistics);
		});
	}

}
